/*
 * @(#)PresenceListener.java 0.0.1-SNAPSHOT
 *
 * Copyright Group B
 */

package grupb.upf.ms.listeners;

import grupb.upf.ms.InstantMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;

/**
 * <p>This component implements a PacketListener Interface. It updates the
 * state of the other users.</p>
 *
 * @version    0.0.1-SNAPSHOT
 * @author     Group B
 */
public final class PresenceListener implements org.jivesoftware.smack
        .PacketListener {
    /**
     * The logger. A new logger <code>grupb.upf.ms.PresenceListener</code>
     * is created to add the logs of this class.
     */
    private static final Log LOG =
            LogFactory.getLog(PresenceListener.class);
    /**
     * The instant message interface to modify the list of connected users.
     */
    private InstantMessage im;

    /**
     * The constructor of the class.
     * @param instantMessage the instant message system.
     */
    public PresenceListener(final InstantMessage instantMessage) {
        this.im = instantMessage;
    }
/**
 * This method controls if the users are online or not.
 * @param packet The packet
 */
    @Override
    public void processPacket(final Packet packet) {
        // Put the incoming message on the chat history or chat board.
        final Presence presence = (Presence) packet;
        final String user = presence.getFrom();
        if (presence.getStatus().equalsIgnoreCase("P2Piki connection")
                && presence.isAvailable()) {
            if (LOG.isInfoEnabled()) {
                final StringBuffer sb =
                        new StringBuffer("Presence message received: ")
                        .append(presence.getStatus())
                        .append(" of user ").append(user);
                LOG.info(sb);
            }
            if (!this.im.getConnectedUsers().contains(user)) {
                this.im.addConnectedUser(user);
            } else {
                if (LOG.isInfoEnabled()) {
                    final StringBuffer sb = new StringBuffer("User ")
                            .append(user).append(" has entered many times");
                    LOG.info(sb);
                }
            }
        } else if (presence.getType() == Presence.Type.unavailable
                && this.im.getConnectedUsers().contains(user)) {
            this.im.setDisconnectedUser(user);
            if (LOG.isInfoEnabled()) {
                final StringBuffer sb = new StringBuffer("User ")
                        .append(user).append(" has gone");
                LOG.info(sb);
            }
        }
    }
}
